import React from 'react'
import AddTodo from './addTodo'
import TodoList from './todoList'
import FilterTodo from './FilterTodo'
let idNumber = 1;
class Todo extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      todos: [], //整体数据
      status: "all" //用来过滤数据的  all 全部数据 done 已完成 no 未完成数据
    }
  }
  // 添加新任务
  addTodoItem = (totext) => {
    console.log("子传父了")
    let arr = [
      {
        id: idNumber++,
        ischeck: false,
        text: totext
      },
      ...this.state.todos
    ]
    console.log(arr)
    this.setState({
      todos: arr
    })
  }
  // 删除列表项
  delTodoItem = (id) => {
    this.state.todos.forEach((item, index) => {
      if (item.id == id) {
        this.state.todos.splice(index, 1)
      }
    })
    this.setState({
      todos: this.state.todos
    })
  }
  ItemChange = (id) => {//切换完成与未完成状态
    this.state.todos.forEach((item, index) => {
      if (id == item.id) {
        this.state.todos[index].ischeck = !this.state.todos[index].ischeck;
      }
    })
    this.setState({
      todos: this.state.todos
    })
    console.log(this.state.todos)
  }
  setStatus = (sta) => {
    // sta 就是传来的all  done no
    this.setState({
      status: sta
    })
  }

  getFilterTodo = () => { //过滤数据方法 每次页面渲染调用
    let { status } = this.state;
    var arr = this.state.todos.filter((item, index) => {
      if (status == "done") { //返回完成的数据
        return item.ischeck == true
      } else if (status == "no") { //返回未完成的数据
        return item.ischeck == false
      } else { //返回所有数据
        return true
      }
    })
    console.log(arr)
    return arr;
  }
  render () {
    // 页面渲染 不直接渲染 this.state.todos 
    // 而是渲染 通过status过滤出来的数据
    let todoList = this.getFilterTodo(); //赋值过滤好的数据给todoList
    let { status } = this.state;
    return (<div>
      <h1>每日任务清单 {this.state.status}</h1>
      <hr />
      <AddTodo addTodo={this.addTodoItem} />
      <hr />
      <TodoList changeItem={this.ItemChange} del={this.delTodoItem} todos={todoList} />
      <hr />
      <FilterTodo status={status} filterData={this.setStatus} />
    </div>)
  }
}

export default Todo